package com.wzh.gateway.conf;

import com.wzh.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author WZH
 * @title: MyFilter
 * @projectName miaosha
 * @description:
 * @date 2022/2/22
 */
public class MyFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().toString();
        String method = request.getMethod().toString();
        String token = request.getHeaders().getFirst("token");
        if (url.contains("/user/")){
            return chain.filter(exchange);
        }
        if ("OPTION".contains(method)){
            return chain.filter(exchange);
        }
        if (token!=null){
            Claims claims = jwtUtil.parseJWT(token);
            if (claims!=null&&"admin".equals(claims.get("roles"))){
                return chain.filter(exchange);
            }
        }
        return null;
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
